﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;

namespace DashFire
{
  class ResVersionLoader
  {
    public static void LoadClientResVersion()
    {
      string resVersionFilePersistPath = ResLoadHelper.Combine(Application.persistentDataPath,
        ResUpdateConfig.s_ResCachePath + ResUpdateConfig.s_ResVersionClientFile);

      if (ResUpdateControler.s_IsNeedSyncPackage || !File.Exists(resVersionFilePersistPath)) {
        //Note:强制更新或覆盖安装或无此资源时，清空此资源
        ClientResVersionProvider.Instance.Clear();
        ResVersionLoader.SaveClientResVersion();
      } else {
        ClientResVersionProvider.Instance.Clear();
        ClientResVersionProvider.Instance.CollectDataFromDBC(resVersionFilePersistPath);
      }
    }
    public static void MergeClientResVersion() {
      string resversionFile = ResLoadHelper.GetFilePath(ResPathType.Cache, ResUpdateConfig.s_ResVersionFile);
      if (File.Exists(resversionFile)) {
        ClientResVersionProvider.Instance.CollectDataFromDBC(resversionFile);
        ResVersionLoader.SaveClientResVersion();
        File.Delete(resversionFile);
      }
    }
    public static void SaveClientResVersion()
    {
      if (ClientResVersionProvider.Instance != null) {
        string fileContent = ResUpdateConfig.s_ResVersionClientHeader + "\n";
        foreach (ClientResVersionData data in ClientResVersionProvider.Instance.GetArray().Values) {
          if (data != null) {
            string dataStr = string.Format(ResUpdateConfig.s_ResVersionClientFormat + "\n",
              data.m_AssetBundleName, data.m_AssetName, data.m_AssetShortName, data.m_MD5, data.m_Size, data.m_Dependency);
            fileContent += dataStr;
          }
        }
        try {
          string resVersionFilePersistPath = ResLoadHelper.Combine(Application.persistentDataPath,
              ResUpdateConfig.s_ResCachePath + ResUpdateConfig.s_ResVersionClientFile);
          File.WriteAllText(resVersionFilePersistPath, fileContent, Encoding.UTF8);
#if UNITY_APPSTORE && UNITY_IPHONE
          iPhone.SetNoBackupFlag(resVersionFilePersistPath);
#endif
        } catch (System.Exception ex) {
          ResUpdateControler.s_UpdateError = ResUpdateError.ClientResVersion_Save_Error;
          ResLoadHelper.Log("SaveClientResVersion file failed!" + ex);
        }
      }
    }
  }
}
